using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

public class BatchRenameTool : EditorWindow
{
    private string baseName = "Object_";
    private int startNumber = 1;
    private int increment = 1;
    private bool keepOriginalName = false;

    [MenuItem("Tools/基础工具/批量重命名")]
    public static void ShowWindow()
    {
        GetWindow<BatchRenameTool>("批量重命名");
    }

    void OnGUI()
    {
        GUILayout.Label("批量重命名工具", EditorStyles.boldLabel);
        EditorGUILayout.Space();

        baseName = EditorGUILayout.TextField("基础名称", baseName);
        startNumber = EditorGUILayout.IntField("起始数字", startNumber);
        increment = EditorGUILayout.IntField("数字增量", increment);
        keepOriginalName = EditorGUILayout.Toggle("保留原名称", keepOriginalName);

        EditorGUILayout.Space();

        if (GUILayout.Button("重命名选中对象"))
        {
            RenameSelectedObjects();
        }

        // 显示选中对象数量
        GUILayout.Label($"选中对象: {Selection.gameObjects.Length}个", EditorStyles.helpBox);
    }

    void RenameSelectedObjects()
    {
        if (Selection.gameObjects.Length == 0)
        {
            EditorUtility.DisplayDialog("提示", "请先选择要重命名的游戏对象", "确定");
            return;
        }

        // 按在Hierarchy中的顺序排序
        List<GameObject> selectedObjects = new List<GameObject>(Selection.gameObjects);
        selectedObjects.Sort((a, b) => a.transform.GetSiblingIndex().CompareTo(b.transform.GetSiblingIndex()));

        Undo.RecordObjects(selectedObjects.ToArray(), "Batch Rename");

        int currentNumber = startNumber;

        foreach (GameObject obj in selectedObjects)
        {
            string newName = keepOriginalName ? $"{baseName}{currentNumber}_{obj.name}" : $"{baseName}{currentNumber}";
            obj.name = newName;
            currentNumber += increment;
        }

        Debug.Log($"成功重命名 {selectedObjects.Count} 个对象");
    }
}